import {
  Breadcrumb,
  Button,
  Card,
  DatePicker,
  Form,
  Radio,
  Table,
  Tag,
  Space,
  message,
  Modal,
} from 'antd';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { delArticleByIdAPI, getArticlesAPI } from 'api/article';
import React, { useEffect, useRef, useState } from 'react';
import { Link } from 'react-router-dom';

import errorSrc from 'assets/error.png';
import Channel from 'components/Channel';
import { useHistory } from 'react-router-dom';

const { RangePicker } = DatePicker;

export default function ArticleList() {
  const articleStatus = [
    { id: -1, name: '全部', color: 'magenta' },
    { id: 0, name: '草稿', color: 'orange' },
    { id: 1, name: '待审核', color: 'red' },
    { id: 2, name: '审核通过', color: 'green' },
    { id: 3, name: '审核失败', color: 'cyan' },
  ];
  const [articleData, setArticleData] = useState({});

  const loadArticles = async (params) => {
    const res = await getArticlesAPI(params);
    setArticleData(res.data);
  };

  const formDataRef = useRef(null);
  const pageInfoRef = useRef(null);

  const handleChange = (page, pageSize) => {
    pageInfoRef.current = { page, per_page: pageSize };
    loadArticles({ page, per_page: pageSize, ...(formDataRef.current || {}) });
  };

  const handleDelById = (id) => {
    Modal.confirm({
      title: '温馨提示',
      content: '你确定要删除这篇文章？',
      onOk: async () => {
        await delArticleByIdAPI(id);
        const formData = formDataRef.current || {};
        const pageInfoData = pageInfoRef.current || {};
        loadArticles({ ...formData, ...pageInfoData });
        message.success('删除成功', 1);
      },
    });
  };

  useEffect(() => {
    loadArticles();
  }, []);

  const history = useHistory();
  const handleSubmit = (values) => {
    console.log('values  ----->  ', values);
    let formData = { ...values };
    if (values.status === -1) {
      delete formData.status;
    }

    if (values.date) {
      const startTime = values.date[0].startOf('day').format('YYYY-MM-DD HH:mm:ss');
      const endTime = values.date[1].endOf('day').format('YYYY-MM-DD HH:mm:ss');
      formData.begin_pubdate = startTime;
      formData.end_pubdate = endTime;
      delete formData.date;
    }

    formDataRef.current = formData;
    loadArticles(formData);
  };

  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render: (value) => {
        if (!value.images.length) {
          return <img width={100} height={60} src={errorSrc} alt="" />;
        }
        return <img width={100} height={60} src={value.images[0]} alt="" />;
      },
    },

    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (value) => {
        const info = articleStatus.find((item) => item.id === value);
        return <Tag color={info.color}>{info.name}</Tag>;
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      key: 'action',
      render: (value, record, index) => {
        return (
          <Space>
            <Button
              onClick={() => history.push('/edit/' + record.id)}
              shape="circle"
              type="primary"
              icon={<EditOutlined />}
            ></Button>
            <Button
              shape="circle"
              icon={<DeleteOutlined />}
              danger
              onClick={() => handleDelById(record.id)}
            ></Button>
          </Space>
        );
      },
    },
  ];

  return (
    <div style={{ paddingTop: 24 }}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>文章列表</Breadcrumb.Item>
          </Breadcrumb>
        }
        bordered={false}
      >
        <Form
          autoComplete="off"
          onFinish={handleSubmit}
          initialValues={{ status: -1, channel_id: 0 }}
        >
          <Form.Item label="状态" name="status">
            <Radio.Group>
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item label="频道" name="channel_id">
            <Channel style={{ width: 200 }}></Channel>
          </Form.Item>

          <Form.Item name="date" label="日期">
            <RangePicker />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>
        根据筛选条件共查询到 {articleData.total_count} 条结果：
        <Table
          columns={columns}
          dataSource={articleData.results}
          rowKey="id"
          pagination={{
            onChange: handleChange,

            position: ['bottomCenter'],
            current: articleData.page,
            pageSize: articleData.per_page,
            total: articleData.total_count,
          }}
        />
      </Card>
    </div>
  );
}
